package top.zhangjianyong.tools.user;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import top.zhangjianyong.tools.entity.User;
import top.zhangjianyong.tools.utils.AnnotationUtil;
import top.zhangjianyong.tools.utils.ApiResponse;

/**
 * @author ： zhangjianyong
 * @date ： 2022/11/28 3:04 PM
 */
@Slf4j
@Aspect
@Component
@Order(999)
public class UserCheckAspect {

    @Pointcut("execution(* top.zhangjianyong.tools.controller.*.*(..))")
    public void checkPointCut() {

    }

    @Around("checkPointCut()")
    public Object check(ProceedingJoinPoint pjp) {
        VerifyUser verifyUser = AnnotationUtil.getAnnotation(pjp, VerifyUser.class);

        boolean login = verifyUser == null || verifyUser.login();
        boolean admin = verifyUser != null && verifyUser.admin();
        Class<? extends IUser> userType =
                verifyUser == null ? User.class : verifyUser.user();

        if (login) {
            //需要验证
            IUser user = UserHolder.user(userType);
            if (null == user) {
                return ApiResponse.fail(999, "登录已失效，请重新登录");
            }
            if (0 == user.getState()) {
                return ApiResponse.fail("未激活，联系管理员激活");
            }
            if (admin && !user.admin()) {
                return ApiResponse.fail("当前无管理员权限");
            }
        }

        try {
            return pjp.proceed();
        } catch (Throwable e) {
            log.error(e.getMessage(), e);
            return ApiResponse.fail(e.getMessage());
        }
    }


}
